package itqf.dao;


import itqf.dao.impl.AdminDao;
import itqf.entity.Users;
import itqf.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * com.itqf.dao
 * 2020/9/18
 */
public class AdminDaoImpl implements AdminDao {
    QueryRunner qr = new QueryRunner(DruidUtils.getDateSource());
    @Override
    public Users findUser(String username, String upassword) {
        String sql = "select u_id as id,u_name as username,u_password as upassword,u_status as ustatus from user where u_name=? and u_password=?";
        Object[] params = {username,upassword};
        try {
            return qr.query(sql,new BeanHandler<>(Users.class),params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Users> findUserByStatus(int status) {
        String sql = "select u_id as id,u_name as username,u_password as upassword,u_status as ustatus," +
                "u_email as uemail,u_sex as usex,u_role as urole from user where u_status=?";
        try {
            return qr.query(sql,new BeanListHandler<>(Users.class),status);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Users> searchUser(String username,String sex) {
        try {
            if(username==""){
                String sql = "select u_id as id,u_name as username,u_password as upassword,u_status as ustatus," +
                        "u_email as uemail,u_sex as usex,u_role as urole from user where  u_sex=?";
                return qr.query(sql,new BeanListHandler<>(Users.class),sex);
            }else{
                String sql = "select u_id as id,u_name as username,u_password as upassword,u_status as ustatus," +
                        "u_email as uemail,u_sex as usex,u_role as urole from user where u_name=?";
                return qr.query(sql,new BeanListHandler<>(Users.class),username);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int delete(int id) {
        String sql = "delete from user where u_id=?";
        try {
            int i = qr.update(sql, id);
            return i;
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }

    }
}
